//
//  HCYOGGuideDOwnload.m
//  YOGProj
//
//  Created by liyun on 14-7-19.
//  Copyright (c) 2014年 qkong. All rights reserved.
//

#import "HCYOGGuideDOwnload.h"
#import "ASIHTTPRequest.h"
#import "HCMacroDefinition.h"
#import "HCSGdownloader.h"

static NSString *zhFileName = @"HCzh.pdf";
static NSString *enFileName = @"HCen.pdf";

static NSString *zh2FileName = @"HCzh2.docx";
static NSString *en2FileName = @"HCen2.docx";

static NSString *zh3FileName = @"HCzh3.pdf";
static NSString *en3FileName = @"HCen3.pdf";

@interface HCYOGGuideDOwnload ()<UIWebViewDelegate,HCSGdownloaderDelegate>
{
    int select;
    HCSGdownloader  *download;
    UIImage *downComplete;
    UIImage *downLogo;
    UIView *displayView;
    
    UIProgressView *zhProgressIndicator;
    UIProgressView *enProgressIndicator;
    
    UIProgressView *zh2ProgressIndicator;
    UIProgressView *en2ProgressIndicator;
    
    UIProgressView *zh3ProgressIndicator;
    UIProgressView *en3ProgressIndicator;
    
    IBOutlet UIImageView *zhImage;
    IBOutlet UIImageView *enImage;
    
    IBOutlet UIImageView *zh2Image;
    IBOutlet UIImageView *en2Image;
    
    IBOutlet UIImageView *zh3Image;
    IBOutlet UIImageView *en3Image;
}

@end

@implementation HCYOGGuideDOwnload

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)navigationShowLeft
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = NSLocalizedString(@"HC交通服务", @"");
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 30);
    [button setBackgroundImage:[UIImage imageWithContentsOfFile:[BUNDLE pathForResource:@"HCback" ofType:@"png"]] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(navigationShowLeft) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItemleft=[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem=barItemleft;
    
    NSArray *titleArr = @[@"观众指南",@"Specator Guide",@"交通指南",@"Traffic Guide",@"公共交通地图",@"Nanjing 2014 Transport Map"];
    downComplete = [UIImage imageWithContentsOfFile:[BUNDLE pathForResource:@"HCcomplete" ofType:@"png"]];
    downLogo = [UIImage imageWithContentsOfFile:[BUNDLE pathForResource:@"HCdownLogo" ofType:@"png"]];
    
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    
    for (int i = 0; i<6; i++)
    {
        if(![currentLanguage isEqualToString:@"zh-Hans"])
        {
            i++;
        }
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 35+66*i, 105, 35)];
        label.text = titleArr[i];
        label.numberOfLines = 2;
        label.backgroundColor = [UIColor clearColor];
        label.font = NORMAL_FONT(16.0f);
        [self.view addSubview:label];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(123+29, 30+66*i, 130, 45);
        button.tag = i;
        [button setBackgroundImage:[UIImage imageWithContentsOfFile:[BUNDLE pathForResource:@"HCdown_back" ofType:@"png"]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(downloadOrOpen:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        if([currentLanguage isEqualToString:@"zh-Hans"])
        {
            i++;
        }
    }
    
    if([currentLanguage isEqualToString:@"zh-Hans"])
    {
        zhImage = [[UIImageView alloc] initWithFrame:CGRectMake(197, 33, 40, 40)];
        zhImage.image = downLogo;
        [self.view addSubview:zhImage];
        
        zh2Image = [[UIImageView alloc] initWithFrame:CGRectMake(197, 165, 40, 40)];
        zh2Image.image = downLogo;
        [self.view addSubview:zh2Image];
        
        zh3Image = [[UIImageView alloc] initWithFrame:CGRectMake(197, 297, 40, 40)];
        zh3Image.image = downLogo;
        [self.view addSubview:zh3Image];
    }
    else
    {
        en2Image = [[UIImageView alloc] initWithFrame:CGRectMake(197, 231, 40, 40)];
        en2Image.image = downLogo;
        [self.view addSubview:en2Image];
        enImage = [[UIImageView alloc] initWithFrame:CGRectMake(197, 99, 40, 40)];
        enImage.image = downLogo;
        [self.view addSubview:enImage];
        en3Image = [[UIImageView alloc] initWithFrame:CGRectMake(197, 363, 40, 40)];
        en3Image.image = downLogo;
        [self.view addSubview:en3Image];
    }
    
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager=[NSFileManager defaultManager];//创建文件管理器
    [fileManager changeCurrentDirectoryPath:[documentPath stringByExpandingTildeInPath]];
    if([currentLanguage isEqualToString:@"zh-Hans"])
    {
        if ([fileManager fileExistsAtPath:zhFileName])
            zhImage.image = downComplete;
        if ([fileManager fileExistsAtPath:zh2FileName])
            zh2Image.image = downComplete;
        if ([fileManager fileExistsAtPath:zh3FileName])
            zh3Image.image = downComplete;
    }
    else
    {
        if ([fileManager fileExistsAtPath:enFileName])
            enImage.image = downComplete;
        if ([fileManager fileExistsAtPath:en2FileName])
            en2Image.image = downComplete;
        if ([fileManager fileExistsAtPath:en3FileName])
            en3Image.image = downComplete;
    }

}

- (IBAction)downloadOrOpen:(UIButton *)sender
{
    //160 250
    
    select = sender.tag;
    int offY = 15;
    if(sender.tag == 0)
    {
        if(!zhProgressIndicator && (zhImage.image != downComplete))
        {
            zhProgressIndicator = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 10+offY, 260, 20)];
            [self.view addSubview:zhProgressIndicator];
            
            NSURL *url = [[NSURL alloc] initWithString:HCzhUrl];
            download = [[HCSGdownloader alloc] initWithURL:url timeout:60];
            download.flag = 0;
            [download startWithDelegate:self];
        }
        else
        {
            if(zhProgressIndicator.progress < 1 && (zhImage.image != downComplete))
                [[NSNotificationCenter defaultCenter]postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC请勿重复下载", @"")}];
            else
                [self showView:0];
        }
    }
    else if(sender.tag == 1)
    {
        if(!enProgressIndicator  && (enImage.image != downComplete))
        {
            enProgressIndicator = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 76+offY, 260, 20)];
            [self.view addSubview:enProgressIndicator];
            
            NSURL *url = [[NSURL alloc] initWithString:HCenUrl];
            download = [[HCSGdownloader alloc] initWithURL:url timeout:60];
            download.flag = 1;
            [download startWithDelegate:self];
            
        }
        else
        {
            if(enProgressIndicator.progress < 1 && (enImage.image != downComplete))
                [[NSNotificationCenter defaultCenter] postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC请勿重复下载", @"")}];
            else
                [self showView:1];
        }
    }
    else if(sender.tag == 2)
    {
        if(!zh2ProgressIndicator && (zh2Image.image != downComplete))
        {
            zh2ProgressIndicator = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 142+offY, 260, 20)];
            [self.view addSubview:zh2ProgressIndicator];
            
            NSURL *url = [[NSURL alloc] initWithString:HCzh2Url];
            download = [[HCSGdownloader alloc] initWithURL:url timeout:60];
            download.flag = 2;
            [download startWithDelegate:self];
        }
        else
        {
            if(zh2ProgressIndicator.progress < 1 && (zh2Image.image != downComplete))
                [[NSNotificationCenter defaultCenter]postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC请勿重复下载", @"")}];
            else
                [self showView:2];
        }
    }
    else if(sender.tag == 3)
    {
        if(!en2ProgressIndicator  && (en2Image.image != downComplete))
        {
            en2ProgressIndicator = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 208+offY, 260, 20)];
            [self.view addSubview:en2ProgressIndicator];
            
            NSURL *url = [[NSURL alloc] initWithString:HCen2Url];
            download = [[HCSGdownloader alloc] initWithURL:url timeout:60];
            download.flag = 3;
            [download startWithDelegate:self];
            
        }
        else
        {
            if(en2ProgressIndicator.progress < 1 && (en2Image.image != downComplete))
                [[NSNotificationCenter defaultCenter] postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC请勿重复下载", @"")}];
            else
                [self showView:3];
        }
    }
    else if(sender.tag == 4)
    {
        if(!zh3ProgressIndicator && (zh3Image.image != downComplete))
        {
            zh3ProgressIndicator = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 274+offY, 260, 20)];
            [self.view addSubview:zh3ProgressIndicator];
            
            NSURL *url = [[NSURL alloc] initWithString:HCzh3Url];
            download = [[HCSGdownloader alloc] initWithURL:url timeout:60];
            download.flag = 4;
            [download startWithDelegate:self];
        }
        else
        {
            if(zh3ProgressIndicator.progress < 1 && (zh3Image.image != downComplete))
                [[NSNotificationCenter defaultCenter]postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC请勿重复下载", @"")}];
            else
                [self showView:4];
        }
    }
    else
    {
        if(!en3ProgressIndicator  && (en3Image.image != downComplete))
        {
            en3ProgressIndicator = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 340+offY, 260, 20)];
            [self.view addSubview:en3ProgressIndicator];
            
            NSURL *url = [[NSURL alloc] initWithString:HCen3Url];
            download = [[HCSGdownloader alloc] initWithURL:url timeout:60];
            download.flag = 5;
            [download startWithDelegate:self];
            
        }
        else
        {
            if(en3ProgressIndicator.progress < 1 && (en3Image.image != downComplete))
                [[NSNotificationCenter defaultCenter] postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC请勿重复下载", @"")}];
            else
                [self showView:5];
        }
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC打开文件有误(格式不支持)", @"")}];
    NSLog(@"%@",error);
    [self performSelector:@selector(dismisShowView) withObject:nil afterDelay:2];
}

- (void)showView:(int)flag
{
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *fileStr;
    switch (flag) {
        case 0:
            fileStr = zhFileName;
            break;
        case 1:
            fileStr = enFileName;
            break;
        case 2:
            fileStr = zh2FileName;
            break;
        case 3:
            fileStr = en2FileName;
            break;
        case 4:
            fileStr = zh3FileName;
            break;
        case 5:
            fileStr = en3FileName;
            break;
        default:
            break;
    }
    
    
    NSString *filePath=[documentPath stringByAppendingString:[NSString stringWithFormat:@"/%@",fileStr]];
    NSLog(@"filePath--->%@",filePath);
    
    if(displayView)
        displayView = nil;
    displayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    displayView.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0];
    [self.view addSubview:displayView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 320, 40);
    [button setTitle:NSLocalizedString(@"HC单击此处返回", @"") forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [button addTarget:self action:@selector(dismisShowView) forControlEvents:UIControlEventTouchUpInside];
    [displayView addSubview:button];
    
    
    UIWebView *showWeb = [[UIWebView alloc] initWithFrame:CGRectMake(0, 40, 320, self.view.frame.size.height-40)];
    showWeb.delegate = self;
    showWeb.scalesPageToFit = YES;
    showWeb.userInteractionEnabled = YES;
    [displayView addSubview:showWeb];
    [showWeb loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
}

- (void)dismisShowView
{
    if(displayView)
        [displayView removeFromSuperview];
}

////请求成功
//-(void)urlRequestFinished:(ASIHTTPRequest *)request
//{
//    NSData *data=[request responseData];
//
//    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSFileManager *fileManager=[NSFileManager defaultManager];//创建文件管理器
//    [fileManager changeCurrentDirectoryPath:[documentPath stringByExpandingTildeInPath]];
//
//    if([[request.userInfo objectForKey:@"code"] isEqualToString:@"zh"])
//    {
//        [zhProgressIndicator removeFromSuperview];
//        NSString *filePath=[documentPath stringByAppendingString:[NSString stringWithFormat:@"/%@",zhFileName]];
//        [fileManager createFileAtPath:zhFileName contents:Nil attributes:Nil];
//        [data writeToFile:filePath atomically:YES];
//        zhImage.image = [UIImage imageNamed:@"complete.png"];
//
//        NSLog(@"zh-->%@",filePath);
//    }
//    else
//    {
//        [enProgressIndicator removeFromSuperview];
//        NSString *filePath=[documentPath stringByAppendingString:[NSString stringWithFormat:@"/%@",enFileName]];
//        [fileManager createFileAtPath:enFileName contents:Nil attributes:Nil];
//        [data writeToFile:filePath atomically:YES];
//        enImage.image = [UIImage imageNamed:@"complete.png"];
//
//        NSLog(@"en-->%@",filePath);
//    }
//}
////请求失败
//-(void)urlRequestFailed:(ASIHTTPRequest *)request
//{
//    if(zhProgressIndicator)
//        [zhProgressIndicator removeFromSuperview];
//    if(enProgressIndicator)
//        [enProgressIndicator removeFromSuperview];
//
//    NSError *error;
//    error=request.error;
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"HCTIP" object:@{@"HCmsg":@"下载失败，请重新下载！"}];
//}

-(void)HCSGDownloadFinished:(NSData*)fileData
{
    [self success:0 data:fileData];
}

-(void)HCSGDownloadFinished2:(NSData*)fileData
{
    [self success:1 data:fileData];
}

-(void)HCSGDownloadFinished3:(NSData*)fileData
{
    [self success:2 data:fileData];
}

-(void)HCSGDownloadFinished4:(NSData*)fileData
{
    [self success:3 data:fileData];
}

-(void)HCSGDownloadFinished5:(NSData*)fileData
{
    [self success:4 data:fileData];
}

-(void)HCSGDownloadFinished6:(NSData*)fileData
{
    [self success:5 data:fileData];
}


- (void)success:(int)flag data:(NSData *)fileData
{
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *fileStr;
    switch (flag) {
        case 0:
            fileStr = zhFileName;
            break;
        case 1:
            fileStr = enFileName;
            break;
        case 2:
            fileStr = zh2FileName;
            break;
        case 3:
            fileStr = en2FileName;
            break;
        case 4:
            fileStr = zh3FileName;
            break;
        case 5:
            fileStr = en3FileName;
            break;
        default:
            break;
    }
    
    NSString *name = [NSString stringWithFormat:@"%@/",fileStr];
    NSString *appFile = [documentPath stringByAppendingPathComponent:name];
    if(![[NSFileManager defaultManager] fileExistsAtPath:appFile])
    {
        [[NSFileManager defaultManager] createFileAtPath:appFile contents:Nil attributes:Nil];
        [fileData writeToFile:appFile atomically:YES];
        NSLog(@"fileData-->%d",fileData.length);
    }
    NSLog(@"appFile-->%@",appFile);
}

-(void)HCSGDownloadProgress:(float)progress Percentage:(NSInteger)percentage
{
    [zhProgressIndicator setProgress:progress animated:YES];
    if(percentage == 100)
    {
        [zhProgressIndicator removeFromSuperview];
        zhImage.image = downComplete;
    }
}

-(void)HCSGDownloadProgress2:(float)progress Percentage2:(NSInteger)percentage
{
    [enProgressIndicator setProgress:progress animated:YES];
    if(percentage == 100)
    {
        [enProgressIndicator removeFromSuperview];
        enImage.image = downComplete;
    }
}

-(void)HCSGDownloadProgress3:(float)progress Percentage3:(NSInteger)percentage
{
    [zh2ProgressIndicator setProgress:progress animated:YES];
    if(percentage == 100)
    {
        [zh2ProgressIndicator removeFromSuperview];
        zh2Image.image = downComplete;
    }
}

-(void)HCSGDownloadProgress4:(float)progress Percentage4:(NSInteger)percentage
{
    [en2ProgressIndicator setProgress:progress animated:YES];
    if(percentage == 100)
    {
        [en2ProgressIndicator removeFromSuperview];
        en2Image.image = downComplete;
    }
}

-(void)HCSGDownloadProgress5:(float)progress Percentage5:(NSInteger)percentage
{
    [zh3ProgressIndicator setProgress:progress animated:YES];
    if(percentage == 100)
    {
        [zh3ProgressIndicator removeFromSuperview];
        zh3Image.image = downComplete;
    }
}

-(void)HCSGDownloadProgress6:(float)progress Percentage6:(NSInteger)percentage
{
    [en3ProgressIndicator setProgress:progress animated:YES];
    if(percentage == 100)
    {
        [en3ProgressIndicator removeFromSuperview];
        en3Image.image = downComplete;
    }
}

-(void)HCSGDownloadFail:(NSError*)error
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HCTIP" object:@{@"HCmsg":NSLocalizedString(@"HC下载失败，请重新尝试", @"")}];
}

@end
